package fun.ticsmyc.multiThread;

import java.io.IOException;
import java.net.*;

/**
 * UDP客户端
 * @author Ticsmyc
 * @package fun.ticsmyc.multiThread
 * @date 2020-03-12 11:20
 */
public class Client  {

    private DatagramSocket datagramSocket;
    private InetAddress address ;
    private int port;

    public Client(){
        this(18888,"127.0.0.1");
    }
    public Client(int port, String netAddress){
        try {
            this.port=port;
            datagramSocket = new DatagramSocket(); //发送端口可以不指定
            address=InetAddress.getByName(netAddress);

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }


    public void send(String requestParam) {
        try {
            DatagramPacket datagramPacket = new DatagramPacket(requestParam.getBytes(), requestParam.length(),address,port);
            datagramSocket.send(datagramPacket);

            String[] str =requestParam.split("\n");
            System.out.print("send: ");
            for(String s:str){
                System.out.print(s+" ");
            }
            System.out.println();

            byte[] receiveBuff = new byte[1024];
            DatagramPacket receivePaket = new DatagramPacket(receiveBuff,receiveBuff.length);
            datagramSocket.receive(receivePaket);
            String receiveParam = new String(receivePaket.getData(),0,receivePaket.getLength());
            System.err.println("receive :"+receiveParam);
            System.out.println();

        } catch (SocketException | UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        Client client = new Client();

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                for (int i = 3; i < 5; ++i) {
                    for (int j = 3; j < 5; ++j) {
                        StringBuilder sb = new StringBuilder();
                        sb.append("x\n");
                        sb.append(i);
                        sb.append("\n");
                        sb.append(j);
                        sb.append("\n");
                        client.send(sb.toString());
                    }
                }
            }
        };

        for(int i=0;i<3;++i){
            new Thread(runnable).start();
        }


    }
}
